
import { EffectManager } from "../../Manager/EffectManager";
import LoadManager from "../../Manager/LoadManager";
import PoolUtil from "../../Utils/PoolUtil";
import { PREFAB } from "../../const/const";
import DialogBase from "./DialogBase";
import Tip from "./Tip";



interface ITipTxt{
    label:string,
    color:string
}


const { ccclass, property, disallowMultiple, menu } = cc._decorator;

@ccclass
@disallowMultiple
export default class Layer extends cc.Component {

    public static inst: Layer = null;

    @property(cc.Node) private dialogLayer: cc.Node = null;
    @property(cc.Node) private loadingLayer: cc.Node = null;

    protected onLoad(): void {
        Layer.inst = this;
        this.hideLoading();
    }

    protected onDestroy(): void {
        Layer.inst = null;
    }

    resetInEditor(){
        this.dialogLayer = this.node.getChildByName("UI");
        this.loadingLayer = this.node.getChildByName("LoadingLayer");
    }
    /**
       * 打开弹窗
       * @async
       * @param url prefab路径，规则同Res加载路径
       * @param args DialogBase.open调用参数
       */
    public async openDialogAsync(url: string, outName:string,callBack:Function,...args: any[]): Promise<void> {
        let node: cc.Node = PoolUtil.get(outName);
        if(node){
            console.log("对象池中找到~~~~~");
        }
        if (!node) {
            this.showLoading();
            let prefab: cc.Prefab = await LoadManager.load(url, cc.Prefab);
            this.hideLoading();
            if (!prefab) {
                cc.error(`[Layer.openDialogAsync] can not find dialog prefab: ${url}`);
                return;
            }
            node = LoadManager.instantiate(prefab);
        }

        this.dialogLayer.addChild(node);
        node.setPosition(0, 0);
        let cmpt:DialogBase= node.getComponent(DialogBase);
        if(callBack){
            callBack(node);
        }
        if (cmpt) {
            //@ts-ignore
            cmpt.popName = outName;
        }
        
    }
    _loadingCount=0;
    showLoading(){
        this._loadingCount++;
        if (!this.loadingLayer.active) {
            this.loadingLayer.active = true;
        }
    }
    hideLoading(){
        this._loadingCount--;
        if (this._loadingCount <= 0) {
            this._loadingCount = 0;
            this.loadingLayer.active = false;
            this.unscheduleAllCallbacks();
        }
    }


     /**
     * 打开唯一弹窗--同一弹窗节点只能同时存在一个
     * @async
     * @param url prefab路径，规则同Res加载路径
     * @param args DialogBase.open调用参数
     */
    public async  openUniDialogAsync(url: string,popName:string,callBack:Function,...args: any[]): Promise<void> {
        if (this.getDialog(url,popName)) {
            return;
        }
        await this.openDialogAsync(url,popName,callBack,...args);
    }

    /**
     * 获取弹窗组件（返回遍历到的第一个）
     * @param url prefab路径，规则同Res加载路径
     */
    public getDialog(url: string,popName:string): DialogBase {
        for (let i = 0; i < this.dialogLayer.childrenCount; i++) {
            let node = this.dialogLayer.children[i];
            let cmpt = node.getComponent(DialogBase);
            if (!cmpt) {
                continue;
            }
            if (cmpt.popName === popName) {
                return cmpt;
            }
        }
        return null;
    }

    
    //提示
    async showTip(...args: ITipTxt[]) {
        let prefab: cc.Prefab = await LoadManager.load(PREFAB.tip, cc.Prefab);
        let node = LoadManager.instantiate(prefab);
        node.getComponent(Tip).initTipUI(args)
        this.dialogLayer.addChild(node);
        node.setPosition(0, 0);
    }
    //
    
    //金币飞入动效
    circleNor: any = [
        cc.v3(90, 55), cc.v3(31, 84),
        cc.v3(97, 1), cc.v3(-16, 133),
        cc.v3(87, -63), cc.v3(-90, 100),
        cc.v3(37, -97), cc.v3(-101, 36),
        cc.v3(-66, -20), cc.v3(-33, -84),
    ];
    /**
     * 
     * @param soundURl :声音路径
     * @param url :金币预设体
     * @param targetPos 目标位置（Canvas下节点）
     */
    async coinFly(soundURl:string,url: string, targetPos: cc.Vec3) {
        // 过滤参数
        let prefab: cc.Prefab = await LoadManager.load(url, cc.Prefab);
        let count = this.circleNor.length;
        let array = [];
        let delayArr = [];
        EffectManager.inst.playEffect(soundURl, false, 1)
        for (let i = 0; i < count; i++) {
            let copy: cc.Node = LoadManager.instantiate(prefab);
            copy.setPosition(cc.v3(0, 0));
            copy.zIndex = 10;
            cc.find('Canvas').addChild(copy);
            array.push(copy);
            delayArr.push(0.05 * i);
        }

        for (let i = 0; i < array.length; i++) {
            let node: cc.Node = array[i];
            let x = this.circleNor[i].x;
            let y = this.circleNor[i].y;
            let delay = delayArr[i]
            cc.tween(node).to(0.5, { position: cc.v3(x, y) }).delay(delay).to(0.5, { position: targetPos }).call(() => {
                node.destroy();
            }).start();
        }
    }
}
